package com.jindun.common;

import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public class StringUtil {

	static Pattern PLUS_FLOAT_PATTERN = Pattern
			.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");

	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	public static String removeComma (String src) {
		if (!isEmpty(src)) {
			return src.replaceAll(",", "");
		}
		return src;
	}
	public static boolean isPlusNumber(String text) {
		if (isEmpty(text)) {
			return false;
		}
		return PLUS_FLOAT_PATTERN.matcher(text).matches();
	}
	public static boolean isPlusInt (String text) {
		try {
		   int value = Integer.valueOf(text.trim());
		   return value > 0;
		} catch (Exception e) {
		   return false;
		}
	}
	
	public static String format(double num, int scale) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(scale);
		nf.setMinimumFractionDigits(scale);
		nf.setGroupingUsed(false);
		return nf.format(num);
	}
	
	public static String format(Date date) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(date);
	}
	
	public static String nvl(String value, String defaultValue) {
		if (isEmpty(value)) {
			return defaultValue;
		} else {
			return value;
		}
		
	}
	
	public static double nvl(Double value, double defaultValue) {
		if (value == null) {
			return defaultValue;
		} else {
			return value;
		}
		
	}
	
	public static int nvl(Integer value, int defaultValue) {
		if (value == null) {
			return defaultValue;
		} else {
			return value;
		}
		
	}
	
	public static String concat (List<Double> list, String seperator) {
		
		if (list == null || list.isEmpty()) {
			return "";
		}
		
		StringBuilder buf = new StringBuilder ();
		Iterator<Double> it = list.iterator();
		
		while (it.hasNext()) {
			buf.append(it.next());
			if (it.hasNext()) {
				buf.append(seperator);
			}
		}

		return buf.toString();
		
		
		
	}
	
}
